package com.hzit.alipayfront.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.hzit.alipayfront.config.AlipayFrontConfig;
import com.hzit.payweb.api.alipay.AliapyQrCodeReq;
import com.hzit.payweb.api.alipay.AlipayH5Req;
import com.hzit.payweb.api.resp.PayFrontRespData;
import com.hzit.payweb.api.resp.RespVo;
import com.hzit.payweb.api.resp.data.PayQueryRespData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 对接支付宝支付接口
 */
@RestController
@RequestMapping("/alipay")
public class AlipayPaymentController {


    @Autowired
    private AlipayFrontConfig alipayFrontConfig;


    /**
     * 支付宝扫码支付：
     * @return
     */
    @RequestMapping("/qrCodePay")
    public RespVo<PayFrontRespData> alipayQrCodePay(@RequestBody AliapyQrCodeReq aliapyQrCodeReq){
        System.out.println("-------------支付宝扫码支付----------");

        RespVo<PayFrontRespData> respVo= new RespVo<PayFrontRespData>();
        //1.封装请求参数、

        //2.调用接口

        //3.解析接口返回参数

        //4.封装对象返回
        return respVo;
    }



    /**
     * 支付宝wap支付：
     * @return
     */
    @RequestMapping("/h5Pay")
    public RespVo<PayFrontRespData> alipayH5Pay(@RequestBody AlipayH5Req h5Req){

        //1.请求参数空判断
        AlipayClient alipayClient = new DefaultAlipayClient(alipayFrontConfig.getServerUrl(),alipayFrontConfig.getAppId(),
                alipayFrontConfig.getYourPrivateKey(),"json","utf-8",alipayFrontConfig.getAlipayPublicKey(),alipayFrontConfig.getSignType());
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setReturnUrl("http://www.baidu/com"); //支付完成后，跳转页面，前端回调,看到页面跳转
        request.setNotifyUrl(h5Req.getNotifyUrl());  //异步回调地址，后端回调地址。用来更新交易结果,看不效果
        JSONObject object = new JSONObject();

        object.put("out_trade_no",h5Req.getOutTraderNo());
        object.put("total_amount",h5Req.getTotalAmt());
        object.put("quit_url",h5Req.getQuitUrl());  //中断的时候，跳页面
        object.put("product_code",h5Req.getProductCode());

        request.setBizContent(object.toJSONString());

        AlipayTradeWapPayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);

        } catch (AlipayApiException e) {
            e.printStackTrace(); //不允许用这个 ,logger.error
            return RespVo.returnFail(-1,e.getErrMsg());
        }

//        RespVo<PayFrontRespData>  respDataRespVo = new RespVo<PayFrontRespData>();

        if(!response.isSuccess()){

            return RespVo.returnFail(-1,response.getSubMsg());
        }
        RespVo respVo1 =  RespVo.returnSuccess("请求成功");
        PayFrontRespData respData = new PayFrontRespData();
        respData.setOutTradeNo(response.getOutTradeNo());
        respData.setPayUrl(response.getBody()); //form 表单
        respVo1.setData(respData);
        return  respVo1;



    }

    /**
     *  支付宝宝，单笔支付查询
     * @return
     */
    @RequestMapping("/singleQuery")
    public  RespVo<PayQueryRespData> tradeSingleQuery(@RequestParam("outTradeNo")String outTradeNo,
                                                      @RequestParam("tradeNo")String tradeNo){


        //1.请求参数空判断
        AlipayClient alipayClient = new DefaultAlipayClient(alipayFrontConfig.getServerUrl(),alipayFrontConfig.getAppId(),
                alipayFrontConfig.getYourPrivateKey(),"json","utf-8",alipayFrontConfig.getAlipayPublicKey(),alipayFrontConfig.getSignType());        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no",outTradeNo);
        jsonObject.put("trade_no",tradeNo);

        request.setBizContent(jsonObject.toJSONString());


        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);

            if(!"10000".equals(response.getCode())){
                return RespVo.returnFail(-1,response.getSubMsg());
            }

            RespVo<PayQueryRespData> respVo = RespVo.returnSuccess("查询成功");

            PayQueryRespData queryRespData = new PayQueryRespData();
            queryRespData.setTradeNo(response.getTradeNo());
            queryRespData.setOutTradeNo(response.getOutTradeNo());
            queryRespData.setTotal_amount(response.getTotalAmount());
            queryRespData.setTrade_status(response.getTradeStatus());

            respVo.setData(queryRespData);
            return respVo;
        } catch (AlipayApiException e) {
            //Todo
            return RespVo.returnFail(-1,e.getErrMsg());
        }



    }

    @RequestMapping("/refund")
    public RespVo alipayRefundAmt(@RequestParam("outTradeNo")String outTradeNo,
                                      @RequestParam("refundAmount")String refundAmount,
                                      @RequestParam("refundSerialNo")String refundSerialNo){
        //1.请求参数空判断
        AlipayClient alipayClient = new DefaultAlipayClient(alipayFrontConfig.getServerUrl(),alipayFrontConfig.getAppId(),
                alipayFrontConfig.getYourPrivateKey(),"json","utf-8",alipayFrontConfig.getAlipayPublicKey(),alipayFrontConfig.getSignType());

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject jsonObject = new JSONObject();

        jsonObject.put("out_trade_no",outTradeNo);
        jsonObject.put("refund_amount",refundAmount);
        jsonObject.put("out_request_no",refundSerialNo);  //退款流水号


        request.setBizContent(jsonObject.toJSONString());

        try {
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            System.out.println("getCode  = " + response.getCode());
            System.out.println("getMsg  = " + response.getMsg());
            System.out.println("getSubCode  = " + response.getSubCode());
            System.out.println("getSubMsg  = " + response.getSubMsg());

            //TODO 封装对象
            return RespVo.returnSuccess("退款成功");

        } catch (AlipayApiException e) {
            return RespVo.returnFail(-1,e.getErrMsg());
        }

    }

}
